#include "UWindowManager.h"
#include "UTextureManager.h"
#include "UNonSpaceFillingContainerWindow.h"
#include "ULeafWindow.h"
#include "UPopUpMenu.h"
#include "UDockable.h"
#include "SDL/SDL_image.h"
#include "UCustomWindow.h"
#include "UWindowThemer.h"

using namespace std;

TWindowManager* WindowManager;
int ScreenWidth = 1024; //1400/2;
int ScreenHeight = 768; //1050/2;

TWindowManager::TWindowManager(int Width, int Height, TWindowThemer* wt)
{
	WindowContainer= new TNonSpaceFillingContainerWindow(TRectangle(0,0,Width, Height), NULL, wt, "Main Window");

	Cursors.push_back(GTextureManager->getTexture("Cursors/Normal.png"));
    Cursors.push_back(GTextureManager->getTexture("Cursors/Moving.png"));
    Cursors.push_back(GTextureManager->getTexture("Cursors/Resizing.png"));

	PopUpMenu= NULL;
}


void TWindowManager::NewWindow(int Left, int Top, int Right, int Bottom, TCustomWindow* Window, TWindowThemer *wt, std::string name, int tag)
{
	TLeafWindow* BorderWindow= new TLeafWindow(TRectangle(Left, Top, Right, Bottom), Window, WindowContainer, wt, name, tag);
	Window->setParent(BorderWindow);
	BorderWindow->SetPos(TRectangle(Left, Top, Right, Bottom));
	
	TDockable* WindowWithSameTag;
	if (tag == 0  || ((WindowWithSameTag = FindWindowByTag(tag)) == NULL) )
	{
		WindowContainer->AddChild(BorderWindow);
	}
	else
	{
		if (WindowWithSameTag->Parent == WindowContainer)
		{
			WindowWithSameTag->Dock(BorderWindow, 
				WindowWithSameTag->Left+ (WindowWithSameTag->Width())/2+2, 
				WindowWithSameTag->Top +  (WindowWithSameTag->Height())/2+2);		
		}
		else
		{
			WindowWithSameTag->Parent->Dock(BorderWindow, 0, 0);
		}
	}


}

TDockable* TWindowManager::FindWindowByTag(int Tag)
{
	return WindowContainer->FindWindowByTag(Tag);
}

void TWindowManager::Draw()
{
	WindowContainer->Draw();
	glRasterPos2i(MPosX-15, MPosY+15);


	if ( (PopUpMenu!=NULL) && (PopUpMenu->Enabled))
		PopUpMenu->Draw(MPosX, MPosY, 0);


	glEnable(GL_BLEND);

	glColor3f(1,1,1);
	glBindTexture(GL_TEXTURE_2D, Cursors[WindowContainer->getCursorType(MPosX, MPosY)]);
	glEnable(GL_TEXTURE_2D);
	glBegin(GL_QUADS);
		glTexCoord2i(0,1); glVertex2i(MPosX-15, MPosY-15);
		glTexCoord2i(1,1); glVertex2i(MPosX+15, MPosY-15);
		glTexCoord2i(1,0); glVertex2i(MPosX+15, MPosY+15);
		glTexCoord2i(0,0); glVertex2i(MPosX-15, MPosY+15);
	glEnd();
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_BLEND);

}

void TWindowManager::EventHandle(SDL_Event event)
{
	if(event.type == SDL_MOUSEMOTION)
	{
		MPosX = event.motion.x;
		MPosY = event.motion.y;
	}
	if ( (PopUpMenu!=NULL) && (PopUpMenu->Enabled))
		PopUpMenu->EventHandle(event);
	WindowContainer->EventHandle(event);

}

